(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.lookup.piController', piController);
	piController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig',
			'authService' ];
	function piController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService) {
		var ctrl = this;
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.ok = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.selectedRows) !== false) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			if(ctrl.dialogsModule.params.multiSelect == "true"){
				ctrl.gridOptions.multiSelect = true;
			}
			if(ctrl.dialogsModule.params.dataType){
				if(ctrl.dialogsModule.params.dataType =="INVOICE-PAYMENT-BATCH"){
					ctrl.gridOptions.multiSelect = true;
				}
				ctrl.searchCriteria.dataType = ctrl.dialogsModule.params.dataType;
			}
			if(ctrl.dialogsModule.params.sellerCode){
				ctrl.searchCriteria.sellerCode = ctrl.dialogsModule.params.sellerCode;
			}
			if(ctrl.dialogsModule.params.payCcy){
				ctrl.searchCriteria.piCcy = ctrl.dialogsModule.params.payCcy;
			}
			ctrl.searchCriteria.piIds = [];
			if (ctrl.dialogsModule.params.piIds) {
				if(angular.isArray(ctrl.dialogsModule.params.piIds)){
					ctrl.searchCriteria.filterPiIds = ctrl.dialogsModule.params.piIds;// get params from parent page
				}
			}
			ctrl.search();
		};

		ctrl.search = function() {
			ctrl.searchCriteria.list = [];
			authService.search(ctrl.searchCriteria).then(function(response) {
				angular.merge(ctrl.searchCriteria, response.data);
				gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
			}, angular.noop);
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);